/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.zx.user.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.jeesite.common.codec.DesUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.common.service.CrudService;
import com.jeesite.common.service.ServiceException;
import com.jeesite.common.utils.excel.ExcelImport;
import com.jeesite.modules.zx.user.entity.ZxUser;
import com.jeesite.modules.zx.user.dao.ZxUserDao;
import com.jeesite.modules.conf.RedisUtils;
import com.jeesite.modules.file.utils.FileUploadUtils;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.entity.EmployeePost;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.entity.Post;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.EmployeeService;
import com.jeesite.modules.sys.service.OfficeService;
import com.jeesite.modules.sys.service.PostService;
import com.jeesite.modules.sys.service.UserService;

/**
 * 用户表Service
 * @author zpp
 * @version 2020-01-29
 */
@Service
@Transactional(readOnly=true)
public class ZxUserService extends CrudService<ZxUserDao, ZxUser> {
	@Autowired
	private RedisUtils redisUtils;
	@Autowired
	private UserService userService;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private PostService postService;
	@Autowired
	private OfficeService officeService;
	/**
	 * 获取单条数据
	 * @param zxUser
	 * @return
	 */
	@Override
	public ZxUser get(ZxUser zxUser) {
		return super.get(zxUser);
	}
	
	/**
	 * 查询分页数据
	 * @param zxUser 查询条件
	 * @param zxUser.page 分页对象
	 * @return
	 */
	@Override
	public Page<ZxUser> findPage(ZxUser zxUser) {
		return super.findPage(zxUser);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param zxUser
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(ZxUser zxUser) {
		super.save(zxUser);
		// 保存上传图片
		FileUploadUtils.saveFileUpload(zxUser.getId(), "zxUser_image");
		// 保存上传附件
		FileUploadUtils.saveFileUpload(zxUser.getId(), "zxUser_file");
	}
	
	/**
	 * 更新状态
	 * @param zxUser
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(ZxUser zxUser) {
		super.updateStatus(zxUser);
	}
	
	/**
	 * 删除数据
	 * @param zxUser
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(ZxUser zxUser) {
		super.delete(zxUser);
	}

	@Transactional(readOnly = false)
    public String importData(MultipartFile file, Boolean isUpdateSupport) {
    	if(file==null) {
    		throw new ServiceException(text("请选择导入的数据文件！"));
    	}
    	int successNum = 0; int failureNum = 0;
    	StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		try(ExcelImport ei = new ExcelImport(file, 2, 0)) {
			List<ZxUser> list=ei.getDataList(ZxUser.class);
			List<String> mobileList=new ArrayList<String>();
			
			for (ZxUser user : list) {
				String mobile = user.getMobile();
				user.setLoginCode(mobile);
				mobileList.add(mobile);
			}
			ZxUser userEntity=new ZxUser();
			userEntity.getSqlMap().getWhere().and("mobile", QueryType.IN, mobileList);
			List<ZxUser> findList = this.findList(userEntity);
			Employee empEntity=new Employee();
			empEntity.getSqlMap().getWhere().and("emp_code", QueryType.IN, mobileList);
			List<Employee> empList=employeeService.findList(empEntity);
			Set<String> hasSet=new HashSet<String>();
			for(ZxUser entity:findList) {
			    String mobile=entity.getMobile();
			    hasSet.add(mobile);
			}
			Set<String> hasEmp=new HashSet<String>();
			for(Employee emp:empList) {
				String empCode=emp.getEmpCode();
				hasEmp.add(empCode);
			}
			List<ZxUser> userList=new ArrayList<ZxUser>();
			for (ZxUser user : list) {
				String mobile = user.getMobile();
				boolean cts = hasSet.contains(mobile);
				String secretKey = Global.getProperty("shiro.loginSubmit.secretKey");
		 		String encode=DesUtils.encode("123456", secretKey);
		 		user.setPassword(encode);
		 		user.setUserType(EmpUser.USER_TYPE_EMPLOYEE);
				user.setMgrType(EmpUser.MGR_TYPE_NOT_ADMIN);
				user.setRefCode(mobile);
				user.setRefName(user.getUserName());
				if(!cts) {
					successNum++;
					userList.add(user);
					successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginCode() + " 更新成功");
				}else {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、账号 " + user.getLoginCode() + " 已存在");
				}
			}
			if(userList.size()>0) {
			   dao.insertBatch(userList);
			   for(ZxUser user:userList) {
				   String mobi=user.getMobile();
				   Employee emp=new Employee();
				   emp.setEmpCode(user.getMobile());
				   emp.setEmpNo(user.getMobile());
				   emp.setEmpName(user.getUserName());
				   if(hasEmp.contains(mobi)) {
					   emp.setIsNewRecord(false);
				   }else {
					   emp.setIsNewRecord(true);
				   }
				   String posts=user.getEmployeePosts();
				   List<String> postList=new ArrayList<String>();
				   if(StringUtils.isNotBlank(posts)) {
				     String[] split = posts.split(",");
				     for(String key:split) {
				    	 postList.add(key);
				     }
				   }
				   String officeCode = user.getOfficeCode();
				   if(StringUtils.isNotBlank(officeCode)) {
				       Office office = officeService.get(officeCode);
				       if(office==null){
				    	   failureNum++;
							failureMsg.append("<br/>" + failureNum + "、机构" + officeCode + " 不存在");
							continue;
				       }
				       emp.setOffice(office);
				   }
				 if(postList.size()>0) { 
				   Post post=new Post();
				   post.getSqlMap().getWhere().and("post_name", QueryType.IN, postList);
				   List<Post> findList2 = postService.findList(post);
				   List<EmployeePost> employeePostList = new ArrayList<EmployeePost>();
				   for(Post p: findList2) {
					   EmployeePost ep=new EmployeePost();
					   ep.setPostCode(p.getPostCode());
					   employeePostList.add(ep);
				   }
				   emp.setEmployeePostList(employeePostList);
				 } 
				   employeeService.save(emp);
			   }
			}
		} catch (Exception e) {
			e.printStackTrace();
			failureMsg.append("导入失败");
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new ServiceException(failureMsg.toString());
		}else{
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
    }
	
}